package main

import (
	"brood-agent2/conf"
	"brood-agent2/controller"
	"brood-agent2/handlers"
	"brood-agent2/utils"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func ReadyHandler(rw http.ResponseWriter, req *http.Request) {
	// agent健康状态
	res := &controller.JsonResponse{
		Code:    0,
		Data:    nil,
		Message: "success",
	}
	controller.RenderJsonResponse(rw, res)
	return
}

func CheckHandler(rw http.ResponseWriter, req *http.Request) {
	// 检查机器状态，是否可以安装
	// 内核、发行版本、gcc

}

func openHandlers() {
	http.HandleFunc("/lts/brood/agent2/ready", ReadyHandler)
	http.HandleFunc("/lts/brood/agent2/check", CheckHandler)
	http.HandleFunc("/lts/brood/agent2/docker/install", handlers.InstallDockerHandler)
	http.HandleFunc("/lts/brood/agent2/etcd/install", handlers.InstallEtcdHandler)
	http.HandleFunc("/lts/brood/agent2/kube-apiserver/install", handlers.InstallKubeApiServerHandler)
	http.HandleFunc("/lts/brood/agent2/kube-scheduler/install", handlers.InstallKubeSchedulerHandler)
	http.HandleFunc("/lts/brood/agent2/kube-controller-manager/install", handlers.InstallKubeControllerManagerHandler)
	http.HandleFunc("/lts/brood/agent2/kubelet/install", handlers.InstallKubeletHandler)
	http.HandleFunc("/lts/brood/agent2/kube-proxy/install", handlers.InstallKubeProxyHandler)
	http.HandleFunc("/lts/brood/agent2/bash-completion/install", handlers.InstallBashCompletionHandler)
	http.HandleFunc("/lts/brood/agent2/nginx/install", handlers.InstallNginxHandler)
	http.HandleFunc("/lts/brood/agent2/lb-with-nginx/install", handlers.InstallLBNginxHandler)
}

func run() {
	confBytes, _ := json.Marshal(conf.Conf)
	utils.Logger.Info(fmt.Sprintf("Args: %s", string(confBytes)))
	err := utils.CreateDirIfNotExist(conf.Conf.TmpDir, os.FileMode(0755))
	if err != nil {
		utils.Logger.Fatal(err)
	}
	openHandlers()
	err = http.ListenAndServe(":8899", nil)
	if err != nil {
		utils.Logger.Fatal(err)
	}
}

func version() string {
	return "0.1.1"
}

func main() {
	run()
}

// cd && wget http://172.22.71.20:8888/api/file/download/brood-agent2-linux -O brood-agent2-linux && chmod 777 brood-agent2-linux && nohup ./brood-agent2-linux -log-dir /root/ -tmp-dir /root/tmp/ -log-level debug  &
// ps -ef |grep brood-agent2-linux | grep -v grep |awk '{print $2}'|xargs kill -s 9
// /Users/wangxingyuan717/Downloads/
